package com.ruoyi.web.controller.TiebaComments.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.TiebaComments.domain.TiebaComments;
import com.ruoyi.web.controller.TiebaComments.mapper.TiebaCommentsMapper;
import com.ruoyi.web.controller.TiebaComments.service.ITiebaCommentsService;
import com.ruoyi.web.controller.TiebaComments.vo.TiebaCommentsCreateReqVo;
import com.ruoyi.web.controller.TiebaComments.vo.TiebaCommentsListReqVo;
import com.ruoyi.web.controller.TiebaComments.vo.TiebaCommentsListVo;
import com.ruoyi.web.controller.TiebaForums.domain.TiebaForums;
import com.ruoyi.web.controller.TiebaForums.service.ITiebaForumsService;
import com.ruoyi.web.controller.TiebaPosts.domain.TiebaPosts;
import com.ruoyi.web.controller.TiebaPosts.mapper.TiebaPostsMapper;
import com.ruoyi.web.controller.TiebaPosts.service.ITiebaPostsService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户评论帖子Controller
 *
 * @author yong
 * @date 2025-03-09
 */
@Api(tags = "用户-评论帖子")
@RestController
@RequestMapping("/TiebaComments/TiebaComments")
public class TiebaCommentsController extends BaseController {
    @Autowired
    private ITiebaCommentsService tiebaCommentsService;

    @Resource
    private TiebaPostsMapper postsMapper;

    @Resource
    private TiebaCommentsMapper commentsMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询用户评论帖子列表
     */
    @ApiOperation("查询帖子评论列表")
//    @PreAuthorize("@ss.hasPermi('system:TiebaComments:list')")
    @GetMapping("/list")
    @Anonymous
    public TableDataInfo list(TiebaCommentsListReqVo listReqVo) {
        startPage();
        TiebaComments tiebaComments = new TiebaComments();
        tiebaComments.setPostId(listReqVo.getPostId()); // 帖子id
        List<TiebaComments> list = tiebaCommentsService.selectTiebaCommentsList(tiebaComments);

        List<TiebaCommentsListVo> commentsListVos = new ArrayList<>();
        for (TiebaComments tiebaComments1 : list) {
            SysUser sysUser = sysUserMapper.selectUserById(tiebaComments1.getUserId());
            TiebaCommentsListVo tiebaCommentsListVo = new TiebaCommentsListVo();
            tiebaCommentsListVo.setUserImageUrl(sysUser.getAvatar());
            tiebaCommentsListVo.setCommentUser(sysUser.getUserName());
            // 帖子
            TiebaPosts posts = postsMapper.selectById(tiebaComments1.getPostId());
            tiebaCommentsListVo.setTitle(posts.getTitle());
            tiebaCommentsListVo.setImageUrl(posts.getImageUrl());
            tiebaCommentsListVo.setCommentContent(tiebaComments1.getContent());
            tiebaCommentsListVo.setCreateTime(tiebaComments1.getCreateTime());
            // 重新构建
            commentsListVos.add(tiebaCommentsListVo);
        }
//        commentsListVos = commentsListVos.stream().sorted(Comparator.comparing(TiebaCommentsListVo::getCreateTime).reversed()).collect(Collectors.toList());
        return getDataTable(commentsListVos);
    }


    /**
     * 获取用户评论帖子详细信息
     */
    @ApiOperation("获取用户评论帖子详细信息")
    @PreAuthorize("@ss.hasPermi('system:TiebaComments:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tiebaCommentsService.getById(id));
    }

    /**
     * 新增用户评论帖子
     */
    @ApiOperation("新增用户评论帖子")
    @PreAuthorize("@ss.hasPermi('system:TiebaComments:add')")
    @Log(title = "用户评论帖子", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addComment(@RequestBody TiebaCommentsCreateReqVo reqVo) {
        TiebaComments tiebaComments = new TiebaComments();
        tiebaComments.setUserId(getUserId());
        tiebaComments.setDeptId(getDeptId());
        tiebaComments.setPostId(reqVo.getPostId());
        tiebaComments.setContent(reqVo.getContent());
        boolean isSaved = tiebaCommentsService.save(tiebaComments);
        if (isSaved) {
            // 使用 UpdateWrapper 来更新评论数量
            UpdateWrapper<TiebaPosts> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", reqVo.getPostId()).setSql("comment_count = comment_count + 1");
            int rows = postsMapper.update(null, updateWrapper);
            if (rows != 1) {
                throw new RuntimeException("评论数量更新失败");
            }
            return AjaxResult.success("评论成功");
        }
        return AjaxResult.error("评论失败");
    }


    /**
     * 修改用户评论帖子
     */
    @ApiOperation("修改用户评论帖子")
    @PreAuthorize("@ss.hasPermi('system:TiebaComments:edit')")
    @Log(title = "用户评论帖子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TiebaComments tiebaComments) {
        return toAjax(tiebaCommentsService.updateById(tiebaComments));
    }

    /**
     * 删除用户评论帖子
     */
    @ApiOperation("删除用户评论帖子")
    @PreAuthorize("@ss.hasPermi('system:TiebaComments:remove')")
    @Log(title = "用户评论帖子", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tiebaCommentsService.removeByIds(Arrays.asList(ids)));
    }
}
